
#include "add.h"



void message_callback(struct mosquitto *mosq, void *obj, const struct mosquitto_message *message)
{
    if (message != NULL && message->payload != NULL)
    {
        printf("topic:%s\n", message->topic);
        printf("message:%s\n", message->payload);

        // 解析 JSON 消息
        cJSON *json = cJSON_Parse((const char *)message->payload);
        if (json != NULL)
        {
            // 遍历 JSON 对象中的所有键值对
            cJSON *current_element = json->child;
            while (current_element != NULL)
            {
                const char *key = current_element->string;
                cJSON *value = current_element;

                if (cJSON_IsBool(value))
                {
                    printf("%s: %s\n", key, value->valueint ? "true" : "false");
                }
                else if (cJSON_IsNumber(value))
                {
                    printf("%s: %f\n", key, value->valuedouble);
                }
                else if (cJSON_IsString(value))
                {
                    printf("%s: %s\n", key, value->valuestring);
                }
                else
                {
                    printf("%s: unknown type\n", key);
                }

                current_element = current_element->next;
            }

            // 检查 lamp 和 id 的值
            cJSON *lamp = cJSON_GetObjectItemCaseSensitive(json, "lamp");
            cJSON *id = cJSON_GetObjectItemCaseSensitive(json, "id");

            if (lamp != NULL && cJSON_IsBool(lamp) && id != NULL && cJSON_IsNumber(id))
            {
                if (id->valueint == 0)
                {
                    if (lamp->valueint)
                    {
                        led_off();
                    }
                    else
                    {
                        led_on();
                    }
                }
            }
            cJSON *fan = cJSON_GetObjectItemCaseSensitive(json, "fan");
            if (fan != NULL && cJSON_IsBool(fan)) {
                if (fan->valueint) {
                    // 打开风扇
                    write_file("/sys/class/hwmon/hwmon1/pwm1", "100");
                    printf("风扇已打开\n");
                } else {
                    // 关闭风扇
                    write_file("/sys/class/hwmon/hwmon1/pwm1", "0");
                    printf("风扇已关闭\n");
                }
            }
            // 释放 cJSON 对象
            cJSON_Delete(json);
        }
        else
        {
            printf("Error parsing JSON\n");
        }
    }
}

